package uplb.ics.cs190.e2d.time;

import org.lwjgl.Sys;
import org.lwjgl.opengl.Display;

public class OpenGLTimer implements SystemTimer {

	protected int fps = 50;
	protected boolean isRunning;
	
	protected long startTime;
	protected long resolution;
	
	protected FPSCounter fpsCounter;
	
	public OpenGLTimer() {
		this.resolution = Sys.getTimerResolution() / 1000;
		fpsCounter = new FPSCounter();
	}
	
	@Override
	public void start() {
		if(!this.isRunning) {
			this.isRunning = true;
			this.startTime = this.getTime();
		}
	}

	@Override
	public void stop() {
		if(this.isRunning) {
			this.isRunning = false;
		}
	}

	@Override
	public long sleep() {
		Display.sync(fps);
		
		fpsCounter.calculateFPS();
		
		long endTime = this.getTime();
		long elapsedTime = endTime - this.startTime;
		this.startTime = endTime;
		
		return elapsedTime;
	}

	@Override
	public long getTime() {
		return Sys.getTime() / this.resolution;
	}

	@Override
	public void refresh() {
		this.startTime = this.getTime();
	}

	@Override
	public boolean isRunning() {
		return this.isRunning;
	}

	@Override
	public int getCurrentFPS() {
		return this.fpsCounter.getFPS();
	}

	@Override
	public int getFPS() {
		return this.fps;
	}

	@Override
	public void setFPS(int fps) {
		this.fps = fps;
	}
}
